//
//  GAOUserAccountViewModel.swift
//  Weibo28
//
//  Created by 高辰 on 16/5/12.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class GAOUserAccountViewModel: NSObject {

    static let UserAccountViewModel: GAOUserAccountViewModel = GAOUserAccountViewModel()
    
    var userAccount: GAOUserAccount?
    
    override init() {
        //读取之前归档的用户信息
        userAccount = GAOUserAccount.loadUserAccount()
    }
    
    var isLogin: Bool {
        //只写get代表是只读属性
        //判断accesstoken,不为nil代表登录,否则就是未登录
        return accessToken != nil
    }
    
    var accessToken: String? {
        guard let token = userAccount?.access_token else {
            return nil
        }
        //通过比对过期时间与当前时间 来判断accesstoken是否过期
        let result = userAccount?.expiresDate?.compare(NSDate())
        //若比对结果排序为降序则 accesstoken没过期
        if result == NSComparisonResult.OrderedDescending {
            return token
        }else {
            return nil
        }
        
    }
    
    //  获取accesstoken
    func requsetAccesstoken(code: String, complete: (isSuccess: Bool)->()) {
        GAONetworkTools.NetworkTools.requestAccesstoken(code) { (response, error) -> () in
            if (error != nil) {
                print(error)
                complete(isSuccess: false)
                return
            }
            
            guard let dict = response as? [String: AnyObject] else {
                complete(isSuccess: false)
                return
            }
            
            //代码执行到此已获得字典数据
            let userAccount = GAOUserAccount(dict: dict)
//            print(userAccount.access_token)
            
            self.requsetUserInfo(userAccount, complete: complete)
            
        }
    }
    
    func requsetUserInfo(useraccount: GAOUserAccount, complete: (isSuccess: Bool)->()) {
        GAONetworkTools.NetworkTools.requestUserInfo(useraccount) { (response, error) -> () in
            if (error != nil) {
                print(error)
                complete(isSuccess: false)
                return
            }
            
            guard let dict = response as? [String: AnyObject] else {
                complete(isSuccess: false)
                return
            }
            
            useraccount.name = dict["name"] as? String
            useraccount.avatar_large = dict["avatar_large"] as? String
            
            //设置用户数据
            self.userAccount = useraccount
            
            let result = useraccount.saveUserAccount()
            
            if result {
                complete(isSuccess: true)
            }else {
                complete(isSuccess: false)
            }
            
        }
    }
    
    
    
}
